package com.cndw.kungfu.model.task;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.core.CacheCenter;
import com.cndw.kungfu.dao.TaskDao;
import com.cndw.kungfu.dao.TaskModeDao;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Task;
import com.cndw.kungfu.domain.TaskMode;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.vo.TaskVO;

/**
 * 任务管理类
 * 
 * @author fantadust
 * 
 */
@Component
public class TaskManager {

	@Autowired
	private TaskDao taskDao;
	@Autowired
	private TaskModeDao taskModeDao;
	@Autowired
	private CacheCenter cacheCenter;

	/**
	 * 获得角色任务集
	 * 
	 * @param playerId
	 * @return
	 */
	public PlayerTasks getPlayerTasksById(long playerId) {
		return cacheCenter.getPlayerTasksByPlayerId(playerId);
	}

	/**
	 * 初始化一个角色任务集
	 * 
	 * @param playerId
	 * @return
	 */
	public PlayerTasks initPlayerTasks(long playerId) {
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		PlayerTasks playerTasks = new PlayerTasks(playerId);

		playerTasks.setDoingTasks(getDoingTasksFromDb(playerId));
		playerTasks.setEndTaskIds(getENDTaskIdsFromDb(playerId));
		playerTasks.setTaskProgress(player.getDataInfo().getTaskProgress());

		playerTasks.initFirst();

		return playerTasks;
	}

	public TaskMode getModeById(int taskId) {
		return cacheCenter.getTaskModeById(taskId);
	}

	/**
	 * 返回我的任务 vo对象
	 * 
	 * @param playerId
	 * @param npcIds
	 * @param level
	 * @return
	 */
	public List<TaskVO> getNpcsTasksVO(long playerId) {
		
		PlayerTasks playerTasks = getPlayerTasksById(playerId);
		playerTasks.initFirst();
		Set<Integer> taskidS = playerTasks.currentCanDoIds();
		Integer[] ids = taskidS.toArray(new Integer[taskidS.size()]);
		playerTasks.changeIds.clear();

		return Context.getTaskServer().toTaskVO(playerId,false, ids);
	}

	/**
	 * 检测单个任务是否完成
	 * 
	 * @param playerId
	 * @param task
	 * @return
	 */
	public boolean checkOneTask(long playerId, Task task) {
		boolean isReached = true;

		TaskMode taskMode = getModeById(task.getTaskId());

		if (BlankUtils.isBlank(taskMode)) {
			return false;
		}
		isReached = checkIsReached(playerId, taskMode);

		if (isReached) {
			task.setStatus(Task.STATUS_FINISH);
			//updateStatus(task);
			getPlayerTasksById(playerId).changeIds.add(task.getTaskId());
		}

		return isReached;
	}

	public boolean checkIsReached(long playerId, TaskMode taskMode) {
		if (taskMode == null) {
			return false;
		}
		List<TaskCondition> taskConditions = taskMode.getTaskConditionsList();
		if (taskConditions == null) {
			return true;
		}
		for (TaskCondition e : taskConditions) {
			int haveCount = Context.getTaskServer().getTaskCompletion(playerId, e, taskMode.getTaskId());
			if (haveCount <= 0 || haveCount < e.getCount()) {
				return false;
			}
		}

		return true;
	}

	/**
	 * 检查任务状态
	 * 
	 * @param playerId
	 */
	public void checkTaskStatus(long playerId) {
		PlayerTasks playerTasks = getPlayerTasksById(playerId);
		Collection<Task> doingTasks = playerTasks.geTasks();
		for (Task task : doingTasks) {
			if (task.getStatus() == Task.STATUS_DOING) {
				checkOneTask(playerId, task);
			}
		}
	}

	/**
	 * 获取我的当前任务
	 * 
	 * @param playerId
	 * @return
	 */
	public Map<Integer, Task> getDoingTasksFromDb(Long playerId) {
		Map<Integer, Task> mapTasks = new HashMap<Integer, Task>();
		List<Task> tasks = taskDao.getDoingTasks(playerId, Task.STATUS_END);
		if (tasks != null) {
			for (Task e : tasks) {
				mapTasks.put(e.getTaskId(), e);
			}
		}

		return mapTasks;
	}

	/**
	 * 获得完成的任务id
	 * 
	 * @param playerId
	 * @return
	 */
	public Map<Integer, Integer> getENDTaskIdsFromDb(long playerId) {

		try {
			Map<Integer, Integer> endTaskIds = taskDao.getENDTaskIds(playerId, Task.STATUS_END);
			if (endTaskIds != null) {
				return endTaskIds;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new HashMap<Integer, Integer>();
	}

	/**
	 * 进行任务字符转化
	 * 
	 * @param str
	 * @return
	 */
	public String formatNpcString(String str) {
		if (str == null || str.equals("null")) {
			return str;
		}
		Pattern p = Pattern.compile("\\{npc:(\\d+)\\}", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			int index = Integer.parseInt(m.group(1));
			m.appendReplacement(sb, Context.getSceneServer().getNpcById(index).getName());
		}
		m.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 对任务模型的内容进行格式化
	 * 
	 * @param taskMode
	 */
	public void formatConditionsDesc(TaskMode taskMode) {

	}

	/**
	 * 执行接受任务
	 * 
	 * @param playerId
	 * @param taskId
	 * @param status
	 */
	public Task acceptTask(long playerId, int taskId) {
		try {

			PlayerTasks playerTasks = getPlayerTasksById(playerId);
			Task task = null;
			TaskMode taskMode = getModeById(taskId);
			int status = Task.STATUS_DOING;
			if (taskMode.getTaskConditionsList() == null || taskMode.getTaskConditionsList().isEmpty()) {
				status = Task.STATUS_FINISH;
			}

			if (playerTasks.checkDoneOnce(taskId)) {
				task = taskDao.getTask(playerId, taskId);
			}
			if (task != null) {// 之前接受的任务直接更新,不再新增记录
				task.setFinishTime(0);
				task.setStatus(status);
				task.setQuality(0);
				task.setAddTime(TimeProcesser.getUnixTime());

				taskDao.updateStatus(task);

			} else {
				task = new Task();
				task.setPlayerId(playerId);
				task.setTaskId(taskId);
				task.setStatus(status);
				task.setQuality(0);
				task.setAddTime(TimeProcesser.getUnixTime());
				task.setId(taskDao.insert(task).longValue());
			}
			playerTasks.acceptTask(task);
			return task;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Task acceptFinishTask(Task task) {
		try {
			task.setId(taskDao.insert(task).longValue());
			return task;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 更新任务状态
	 * 
	 * @param playerId
	 * @param status
	 * @param id
	 */
	public void updateStatus(Task task) {

		try {
			taskDao.updateStatus(task);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void cancelTask(long playerId, int taskId) {
		try {
			taskDao.delete(playerId, taskId);
		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	/**
	 * 获取全部任务从数据库
	 * 
	 * @return
	 */
	public List<TaskMode> getAllTasksFromDb() {
		List<TaskMode> taskModes = taskModeDao.getAllTasksFromDb();

		return taskModes;
	}



}
